package com.xianyun.book.domain.price;

import lombok.Data;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 汇率转换
 * @author macos-zyj
 */
@Data
public class Currency {
    private static final  String DECIMAL = "(\\d+\\.\\d+)";
    private static final String NUMBER = "\\d+";
    /**待处理字符串*/
    private String dellString;
    /**面额*/
    private String denomination;
    /**货币*/
    private String currency;
    /**汇率*/
    private Double exchangeRate;
    /**总和*/
    private BigDecimal amount;

    public Currency(String dellString){
        this.dellString= dellString.replaceAll(" ","");
        setPriceNumber();
        setCurrencyType();
        setExchangeRate();
    }

    public void setPriceNumber(){
        Pattern pattern = Pattern.compile(DECIMAL);
        Matcher matcher = pattern.matcher(dellString);
        if (matcher.find()) {
            denomination =  matcher.group(0);
        }else {
            pattern = Pattern.compile(NUMBER);
            matcher = pattern.matcher(dellString);
            if (matcher.find()) {
                denomination = matcher.group(0);
            } else {
                denomination = "0";
            }
        }
    }

    public void setCurrencyType(){
        this.currency = dellString.replaceAll(denomination,"");
    }

    public void setExchangeRate(){
        try{
            this.exchangeRate = CurrencyEnum.getChangeRateByType(currency);
        } catch (Exception exception){
            this.exchangeRate = 0.0;
        }
    }

    public BigDecimal getAmount(){
        Double denomination = Double.valueOf(this.denomination);
        return new BigDecimal(denomination*exchangeRate);
    }
}
